package com.test.springCloud.service.impl;

import java.io.File;
import java.util.UUID;

import com.test.springCloud.service.UploadImgService;
import com.test.springCloud.utils.*;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import com.alibaba.fastjson.JSONObject;

import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpResponse;

/**
 *上传文件
 */
@Service("UploadImgService")
public class UploadImgServiceImpl implements UploadImgService {

	@Override
	public String uploadImg(String customPath, String pic64) {
		ImgUtil imgUtil = new ImgUtil();
		CreateFolder createFolder = new CreateFolder();
		// 日期前的路径\\ishenjian_laborattendancelist\\original
		String prefixFolder = imgUtil.imgServerFolder + customPath;
		// 最终路径\\ishenjian_laborattendancelist\\original\\20210618
		String formalPath = createFolder.CreateFolderBasedOnTheToday(prefixFolder);
		// 拼接加上文件名
		String guid = UUID.randomUUID().toString().replace("-", "");
		formalPath += "/" + guid + ".jpg";

		// 获得
		String savePath = imgUtil.GenerateImage(pic64, formalPath);
		if (savePath == null)
			return null;
		return savePath;
	}

	@Override
	public JSONObject filterToConfirm(String pic64) {
		boolean a = RegularUtil.matchingBase64ForHeadBeginning(pic64);
		boolean b = RegularUtil.matchingBase64ForMainBeginning(pic64);
		JSONObject jsonObject = new JSONObject();
		if (!(a | b)) {
			jsonObject.put("code", 500);
			jsonObject.put("message", "参数不是base64，请检查重新上传。");
			return jsonObject;
		}
		if (a) {
			pic64 = RegularUtil.getRidOfBase64ForDataBeginning(pic64);
			jsonObject.put("code", 200);
			jsonObject.put("message", "ok");
			jsonObject.put("data", pic64);
			return jsonObject;
		}
		jsonObject.put("code", 500);
		jsonObject.put("message", "未知原因");
		return jsonObject;
	}

	/**
	 * 上传图片，然后保存，返回JSON
	 */
	@Override
	public JSONObject uploadAndStoreDefaultImgToWeb(MultipartFile file) {

		JSONObject jsonObject = new JSONObject();

		String remoteUrl = "mangerapi.yishun618.com/imgServer/uploadDefaultPicAndReturnImgUrl";
		String url = remoteUrl;

		File file2 = null;
		try {
			file2 = new MultipartFileToFile().multipartFileToFile(file);
			if (file2 == null) {
				jsonObject.put("code", 0);
				jsonObject.put("message", "传入文件为空");
				return jsonObject;
			}
		} catch (Exception e) {
			e.printStackTrace();
			jsonObject.put("code", 0);
			jsonObject.put("message", "后台错误：文件为空的例外情况");
			return jsonObject;
		}
		HttpResponse response = HttpRequest.post(url).form("file", file2).execute();

		String responseStr = response.body().toString();

		MatchStrUtil parentStr = new MatchStrUtil();
		if (parentStr.parent502NetFalid(responseStr)) {
			jsonObject.put("code", 0);
			jsonObject.put("message", "上传图片到所请求的服务器网关出错（502服务器未开启）");
			return jsonObject;
		}

		return JSONObject.parseObject(responseStr);

	}

	@Override
	public String storeLocalDefaultImg(MultipartFile file) {
		JSONObject jsonObject = new JSONObject();

		System.out.println("file length:" + file.getSize());
		if (file == null) {
			jsonObject.put("code", 0);
			jsonObject.put("message", "文件为空");
			return jsonObject.toJSONString();
		}

		StoreFile storeFile = new StoreFile(); // 调用存储文件工具类
//		String storeFilepath = "D:\\webserver\\nginx-1.19.6\\imgserver\\platform_manger\\Default\\original";// 存放文件的文件夹
		ImgUtil imgUtil = new ImgUtil();
		// 创建年月日文件夹
		String storeFilepath = null;
		try {
			storeFilepath = imgUtil.createFileFolder(imgUtil.imgServerFolder + "\\platform_manger\\Default\\original");
		} catch (java.text.ParseException e) {
			e.printStackTrace();
		} // 存放文件的文件夹
		String picUri = storeFile.storeFile(file, storeFilepath);// 保存在文件夹
		// 保存文件失败则返回
		if (picUri == null) {
			jsonObject.put("code", 422);
			return jsonObject.toJSONString();
		}

		// 拼接远程图片地址
		String remotePicUri = imgUtil.imgServersUrl
				+ picUri.replace(imgUtil.imgServerFolder, "").replaceAll("\\\\", "/");

		jsonObject.put("code", 200);
		jsonObject.put("message", "成功");
		JSONObject dataObject = new JSONObject();
		dataObject.put("remotePicUri", remotePicUri);
		jsonObject.put("data", dataObject);
		return jsonObject.toJSONString();
	}

	@Override
	public String storeCrsLocalDefaultImg(MultipartFile file) {
		JSONObject jsonObject = new JSONObject();

		System.out.println("file length:" + file.getSize());
		if (file == null) {
			jsonObject.put("code", 0);
			jsonObject.put("message", "文件为空");
			return jsonObject.toJSONString();
		}

		StoreFile storeFile = new StoreFile(); // 调用存储文件工具类
//		String storeFilepath = "D:\\webserver\\nginx-1.19.6\\imgserver\\platform_manger\\Default\\original";// 存放文件的文件夹
		ImgUtil imgUtil = new ImgUtil();
		// 创建年月日文件夹
		String storeFilepath = null;
		try {
			storeFilepath = imgUtil
					.createFileFolder(imgUtil.imgServerFolder + "\\customizedRealNameSystemservice\\Default\\original");
		} catch (java.text.ParseException e) {
			e.printStackTrace();
		} // 存放文件的文件夹
		String picUri = storeFile.storeFile(file, storeFilepath);// 保存在文件夹
		// 保存文件失败则返回
		if (picUri == null) {
			jsonObject.put("code", 422);
			return jsonObject.toJSONString();
		}

		// 拼接远程图片地址
		String remotePicUri = imgUtil.imgServersUrl
				+ picUri.replace(imgUtil.imgServerFolder, "").replaceAll("\\\\", "/");

		jsonObject.put("code", 200);
		jsonObject.put("message", "成功");
		JSONObject dataObject = new JSONObject();
		dataObject.put("remotePicUri", remotePicUri);
		jsonObject.put("data", dataObject);
		return jsonObject.toJSONString();
	}

	@Override
	public String storeLocalfaceAttendanceOtherImg(MultipartFile file) {
		JSONObject jsonObject = new JSONObject();

		if (file == null) {
			jsonObject.put("code", 0);
			jsonObject.put("message", "文件为空");
			return jsonObject.toJSONString();
		}

		StoreFile storeFile = new StoreFile(); // 调用存储文件工具类
//		String storeFilepath = "D:\\webserver\\nginx-1.19.6\\imgserver\\platform_manger\\Default\\original";// 存放文件的文件夹
		ImgUtil imgUtil = new ImgUtil();
		// 创建年月日文件夹
		String storeFilepath = null;
		try {
			storeFilepath = imgUtil.createFileFolder(
					imgUtil.imgServerFolder + "\\platform_manger\\localface_attendance_other\\original");
		} catch (java.text.ParseException e) {
			e.printStackTrace();
		} // 存放文件的文件夹
		String picUri = storeFile.storeFile(file, storeFilepath);// 保存在文件夹
		// 保存文件失败则返回
		if (picUri == null) {
			jsonObject.put("code", 422);
			return jsonObject.toJSONString();
		}

		// 拼接远程图片地址
		String remotePicUri = imgUtil.imgServersUrl
				+ picUri.replace(imgUtil.imgServerFolder, "").replaceAll("\\\\", "/");

		jsonObject.put("code", 200);
		jsonObject.put("message", "成功");
		JSONObject dataObject = new JSONObject();
		dataObject.put("remotePicUri", remotePicUri);
		jsonObject.put("data", dataObject);
		return jsonObject.toJSONString();
	}

	@Override
	public String storeLocalCustomImg(MultipartFile file, String customFolder) {
		JSONObject jsonObject = new JSONObject();

		if (file == null) {
			jsonObject.put("code", 0);
			jsonObject.put("message", "文件为空");
			return jsonObject.toJSONString();
		}

		StoreFile storeFile = new StoreFile(); // 调用存储文件工具类
//		String storeFilepath = "D:\\webserver\\nginx-1.19.6\\imgserver\\platform_manger\\Default\\original";// 存放文件的文件夹
		ImgUtil imgUtil = new ImgUtil();
		// 创建年月日文件夹
		String storeFilepath = null;
		try {
			storeFilepath = imgUtil.createFileFolder(imgUtil.imgServerFolder + customFolder);
		} catch (java.text.ParseException e) {
			e.printStackTrace();
		} // 存放文件的文件夹
		String picUri = storeFile.storeFile(file, storeFilepath);// 保存在文件夹
		// 保存文件失败则返回
		if (picUri == null) {
			jsonObject.put("code", 422);
			return jsonObject.toJSONString();
		}

		// 拼接远程图片地址
		String remotePicUri = imgUtil.imgServersUrl
				+ picUri.replace(imgUtil.imgServerFolder, "").replaceAll("\\\\", "/");

		jsonObject.put("code", 200);
		jsonObject.put("message", "成功");
		JSONObject dataObject = new JSONObject();
		dataObject.put("remotePicUri", remotePicUri);
		jsonObject.put("data", dataObject);
		return jsonObject.toJSONString();
	}

	@Override
	public JSONObject uploadAndStoreDefaultImgToWeb(MultipartFile[] file) {
		JSONObject responseObject = new JSONObject();
		JSONObject responseDataObject = new JSONObject();
		Integer successCount = 0;
		JSONObject getInfoObject = null;
		for (int i = 0; i < file.length; i++) {
			getInfoObject = uploadAndStoreDefaultImgToWeb(file[i]);
			// 正确则进入拼装
			if (getInfoObject.getInteger("code") == 200) {
				successCount++;
				responseDataObject.put("remotePicUri" + i,
						getInfoObject.getJSONObject("data").getString("remotePicUri"));
			} else
				responseDataObject.put("remotePicUri" + i, null);
		}
		responseObject.put("successCount", successCount);
		responseObject.put("uploadCount", file.length);
		responseObject.put("data", responseDataObject);
		return responseObject;
	}

	/**
	 * 上传图片，然后保存，返回JSON
	 */
	@Override
	public JSONObject uploadAndStoreDefaultImgToWebIndex(MultipartFile file) {

		JSONObject jsonObject = new JSONObject();

		String remoteUrl = "mangerapi.yishun618.com/imgServer/uploadPlatIndexPicAndReturnImgUrl";
		String url = remoteUrl;

		File file2 = null;
		try {
			file2 = new MultipartFileToFile().multipartFileToFile(file);
			if (file2 == null) {
				jsonObject.put("code", 0);
				jsonObject.put("message", "传入文件为空");
				return jsonObject;
			}
		} catch (Exception e) {
			e.printStackTrace();
			jsonObject.put("code", 0);
			jsonObject.put("message", "后台错误：文件为空的例外情况");
			return jsonObject;
		}
		HttpResponse response = HttpRequest.post(url).form("file", file2).execute();

		String responseStr = response.body().toString();

		MatchStrUtil parentStr = new MatchStrUtil();
		if (parentStr.parent502NetFalid(responseStr)) {
			jsonObject.put("code", 0);
			jsonObject.put("message", "上传图片到所请求的服务器网关出错（502服务器未开启）");
			return jsonObject;
		}

		return JSONObject.parseObject(responseStr);

	}

	@Override
	public JSONObject uploadAndStoreDefaultImgToWebIndex(MultipartFile[] file) {
		JSONObject responseObject = new JSONObject();
		JSONObject responseDataObject = new JSONObject();
		Integer successCount = 0;
		JSONObject getInfoObject = null;
		for (int i = 0; i < file.length; i++) {
			getInfoObject = uploadAndStoreDefaultImgToWebIndex(file[i]);
			// 正确则进入拼装
			if (getInfoObject.getInteger("code") == 200) {
				successCount++;
				responseDataObject.put("remotePicUri" + i,
						getInfoObject.getJSONObject("data").getString("remotePicUri"));
			} else
				responseDataObject.put("remotePicUri" + i, null);
		}
		responseObject.put("successCount", successCount);
		responseObject.put("uploadCount", file.length);
		responseObject.put("data", responseDataObject);
		return responseObject;
	}

	@Override
	public JSONObject uploadAndStoreLocalfaceAttendanceOtherImg(MultipartFile[] file) {
		JSONObject responseObject = new JSONObject();
		JSONObject responseDataObject = new JSONObject();
		Integer successCount = 0;
		JSONObject getInfoObject = null;
		for (int i = 0; i < file.length; i++) {
			getInfoObject = uploadAndStoreLocalfaceAttendanceOtherImg(file[i]);
			// 正确则进入拼装
			if (getInfoObject.getInteger("code") == 200) {
				successCount++;
				responseDataObject.put("remotePicUri" + i,
						getInfoObject.getJSONObject("data").getString("remotePicUri"));
			} else
				responseDataObject.put("remotePicUri" + i, null);
		}
		responseObject.put("successCount", successCount);
		responseObject.put("uploadCount", file.length);
		responseObject.put("data", responseDataObject);
		return responseObject;
	}

	@Override
	public JSONObject uploadAndStoreLocalfaceAttendanceOtherImg(MultipartFile file) {
		JSONObject jsonObject = new JSONObject();

		String remoteUrl = "mangerapi.yishun618.com/imgServer/uploadfaceAttendanceOther";
		String url = remoteUrl;

		File file2 = null;
		try {
			file2 = new MultipartFileToFile().multipartFileToFile(file);
			if (file2 == null) {
				jsonObject.put("code", 0);
				jsonObject.put("message", "传入文件为空");
				return jsonObject;
			}
		} catch (Exception e) {
			e.printStackTrace();
			jsonObject.put("code", 0);
			jsonObject.put("message", "后台错误：文件为空的例外情况");
			return jsonObject;
		}
		HttpResponse response = HttpRequest.post(url).form("file", file2).execute();

		String responseStr = response.body().toString();

		MatchStrUtil parentStr = new MatchStrUtil();
		if (parentStr.parent502NetFalid(responseStr)) {
			jsonObject.put("code", 0);
			jsonObject.put("message", "上传图片到所请求的服务器网关出错（502服务器未开启）");
			return jsonObject;
		}

		return JSONObject.parseObject(responseStr);
	}

	@Override
	public JSONObject uploadAndStoreOtherImgToWebIndex(MultipartFile[] file) {
		JSONObject responseObject = new JSONObject();
		JSONObject responseDataObject = new JSONObject();
		Integer successCount = 0;
		JSONObject getInfoObject = null;
		for (int i = 0; i < file.length; i++) {
			getInfoObject = uploadAndStoreDefaultImgToWebIndex(file[i]);
			// 正确则进入拼装
			if (getInfoObject.getInteger("code") == 200) {
				successCount++;
				responseDataObject.put("remotePicUri" + i,
						getInfoObject.getJSONObject("data").getString("remotePicUri"));
			} else
				responseDataObject.put("remotePicUri" + i, null);
		}
		responseObject.put("successCount", successCount);
		responseObject.put("uploadCount", file.length);
		responseObject.put("data", responseDataObject);
		return responseObject;
	}
}
